package com.example.fresh_market.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.android.volley.Request;
import com.bumptech.glide.request.RequestOptions;
import com.example.fresh_market.databinding.ActivityAccountSettingBinding;
import com.example.fresh_market.entity.UserInfo;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;

public class AccountSettingActivity extends AppCompatActivity {
    private ActivityAccountSettingBinding binding;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        binding = ActivityAccountSettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initEvent();
        initData();
    }

    private void initData() {
        HttpUtil.get(mContext, "/user", response -> {
            ApiResponse<UserInfo> apiResponse = new Gson().fromJson(response, new TypeToken<ApiResponse<UserInfo>>() {
            }.getType());
            if (apiResponse.getCode() == 200) {
                UserInfo userInfo = apiResponse.getData();
                binding.nicknameEditText.setText(userInfo.getNickname());
                binding.phoneEditText.setText(userInfo.getPhone());
                binding.emailEditText.setText(userInfo.getEmail());
                binding.addressEditText.setText(userInfo.getAddress());
                binding.remarkEditText.setText(userInfo.getRemark());
                binding.ageEditText.setText(userInfo.getAge());
                if (userInfo.getGender() == 1) {
                    binding.maleRadioButton.setChecked(true);
                } else if (userInfo.getGender() == 2) {
                    binding.femaleRadioButton.setChecked(true);
                } else {
                    binding.otherRadioButton.setChecked(true);
                }
                if (StringUtils.isNotBlank(userInfo.getAvatar())) {
                    HttpUtil.loadImage(binding.avatarImageView, userInfo.getAvatar(), new RequestOptions());
                }
            }
        });
    }

    private void initEvent() {
        binding.avatarImageView.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, 666);
        });
        binding.saveButton.setOnClickListener(v -> {
            // 获取图片
            Drawable drawable = binding.avatarImageView.getDrawable();
            String cover = null;
            if (drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                cover = Base64.getEncoder().encodeToString(stream.toByteArray());
            }
            UserInfo userInfo = UserInfo.builder()
                    .nickname(binding.nicknameEditText.getText().toString())
                    .phone(binding.phoneEditText.getText().toString())
                    .email(binding.emailEditText.getText().toString())
                    .address(binding.addressEditText.getText().toString())
                    .remark(binding.remarkEditText.getText().toString())
                    .age(binding.ageEditText.getText().toString())
                    .gender(binding.maleRadioButton.isChecked() ? 1 : binding.femaleRadioButton.isChecked() ? 2 : 3)
                    .avatar(cover)
                    .build();
            Gson gson = new Gson();
            HttpUtil.sendJsonRequest(mContext, Request.Method.PUT, "/user", gson.toJson(userInfo), response -> {
                ApiResponse apiResponse = gson.fromJson(response.toString(), ApiResponse.class);
                if (apiResponse.getCode() == 200) {
                    ToastUtil.showToast(mContext, "保存成功");
                    finish();
                }
            });
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 666 && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                try (InputStream inputStream = getContentResolver().openInputStream(imageUri)) {
                    if (inputStream != null) {
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        binding.avatarImageView.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
    }
}
